/* eslint-disable eqeqeq */
/* eslint-disable react/jsx-filename-extension */
import { LoadingOutlined } from '@ant-design/icons';
import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { StepC } from '../../other';
import { uniqueKey } from '@/src/utils/commonFunc';
import { message } from 'antd';

const OrderComponet = (props = {}) => {
  const { dispatch, successMsg = '下达成功！', handleSuccess = () => {}, handleError = () => {}, visible = false, params = {}, tradeType } = props;
  const [nowStep, setNowStep] = useState(0); // 当前步骤
  const [visibleStep, setVisibleStep] = useState(); // 是否可见
  const [status, setStatus] = useState('process'); // 当前状态
  const [errorMsg, setErrorMsg] = useState(''); // 错误消息
  const [errorType, setErrorType] = useState(''); // 错误信息 是更新可用资金-1  还是可用持仓-2

  // 簿记下达 新接口
  const saveOrderNew = (uid) => {
    const timeStamp = new Date().getTime();
    dispatch({
      type: 'businessOrderM/saveOrderNew',
      payload: {
        ...params,
        tradeType,
        id: uid, // 指令id
      },
    }).then((res) => {
      const temp = new Date().getTime();
      const delayFlag = temp - timeStamp < 500; // 拿到实际结果小于2s 等个1s再进入下一个节点
      if (res?.code == 0) {
        // 进入第二个节点
        setTimeout(
          () => {
            setNowStep(1);
            // 如果下达接口成功 则轮询请求验资验券接口
            onCheck(uid);
          },
          delayFlag ? 500 : 0,
        );
      } else {
        // 如果下达接口失败 则页面恢复到点击确定按钮之前
        setTimeout(
          () => {
            setStatus('error');
            setErrorMsg('系统出错，请联系管理员查看问题。');
          },
          delayFlag ? 500 : 0,
        );
      }
    });
  };
  // 查询验资验券结果
  const onCheck = (uid) => {
    const timeStamp = new Date().getTime();
    dispatch({
      type: 'businessOrderM/onCheck',
      payload: { id: uid },
    })
      .then((res) => {
        let msg = '';
        if (res?.code == -1) {
          // 状态在查询中 则继续请求
          let timer = null;
          timer = setTimeout(() => {
            console.log('循环');
            onCheck(uid);
          }, 500);
          return;
        } else if (res?.code == 0) {
          // 验资验券成功 则查询下达结果
          const temp = new Date().getTime();
          const delayFlag = temp - timeStamp < 500; // 拿到实际结果小于2s 等个1s再进入下一个节点
          setTimeout(
            () => {
              setNowStep(2);
              queryResult(uid); // 查询簿记下达结果
            },
            delayFlag ? 500 : 0,
          );
        } else if (res?.code == 1 || res?.code == 2) {
          msg = res.msg || `可用${res.code == 1 ? '资金' : '持仓'}不足，请重新调整交易参数。`;
          setErrorType(res.code); // 保存错误码 用于更新资金或者持仓数据
        } else if (res?.code == 3) {
          msg = res.msg || '关联质押持仓不足';
        } else if (res?.code == 4) {
          msg = res.msg || '系统出错，请联系管理员查看问题。';
        }

        if (msg && res?.code != 0) {
          // 有错误的情况下
          const temp = new Date().getTime();
          const delayFlag = temp - timeStamp < 500; // 拿到实际结果小于2s 等个1s再进入下一个节点
          setTimeout(
            () => {
              setStatus('error');
              setErrorMsg(msg);
            },
            delayFlag ? 500 : 0,
          );
        }
      })
      .catch((e) => {
        console.log('验资验券 error');
      });
  };
  // 查询簿记下达结果
  const queryResult = (uid) => {
    const timeStamp = new Date().getTime();
    dispatch({
      type: 'businessOrderM/queryResult',
      payload: { id: uid },
    })
      .then((res) => {
        console.log(res, 'result');
        if (res?.code == -1) {
          // 状态在查询中 则继续请求
          let timer = null;
          timer = setTimeout(() => {
            console.log('循环res');
            queryResult(uid);
          }, 500);
        } else if (res?.code == 0) {
          // 簿记下达成功
          const temp = new Date().getTime();
          const delayFlag = temp - timeStamp < 500; // 拿到实际结果小于2s 等个1s再进入下一个节点
          setTimeout(
            () => {
              // 通知父组件 下达成功
              handleSuccess();
              message.success(successMsg);
            },
            delayFlag ? 500 : 0,
          );
        } else {
          // 如果下达接口失败 则页面恢复到点击确定按钮之前
          const temp = new Date().getTime();
          const delayFlag = temp - timeStamp < 500; // 拿到实际结果小于2s 等个1s再进入下一个节点
          setTimeout(
            () => {
              setStatus('error');
              setErrorMsg('系统出错，请联系管理员查看问题。');
            },
            delayFlag ? 500 : 0,
          );
        }
      })
      .catch((e) => {
        console.log('下达结果 error');
      });
  };
  // 关闭
  const clickClose = () => {
    handleError(errorType);
  };
  useEffect(() => {
    // 修改弹窗状态
    if (visible) {
      // 调用下达接口
      uniqueKey('new').then((uid) => {
        // 请求指令id
        if (!uid) {
          handleError();
          message.error('系统错误，请联系管理员查看问题。');
          return;
        }
        setVisibleStep(visible);
        saveOrderNew(uid);
      });
    } else {
      setVisibleStep(visible);
      // 重置
      setNowStep(0);
      setStatus('process');
      setErrorMsg('');
      setErrorType('');
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);
  return (
    <StepC
      status={status}
      nowStep={nowStep}
      visible={visibleStep}
      onClose={clickClose}
      items={[
        {
          title: '用户发起',
          disabled: true,
          icon: status == 'process' && nowStep == 0 ? <LoadingOutlined /> : undefined,
          description: status == 'error' && nowStep == 0 ? errorMsg : '',
        },
        {
          title: '验资验券',
          disabled: true,
          icon: status == 'process' && nowStep == 1 ? <LoadingOutlined /> : undefined,
          description: status == 'error' && nowStep == 1 ? errorMsg : '',
        },
        {
          title: '簿记下达',
          icon: status == 'process' && nowStep == 2 ? <LoadingOutlined /> : undefined,
          disabled: true,
          description: status == 'error' && nowStep == 2 ? errorMsg : '',
        },
      ]}
    />
  );
};
OrderComponet.propTypes = {
  // eslint-disable-next-line react/boolean-prop-naming
  visible: PropTypes.bool, // 是否可见
  handleSuccess: PropTypes.func, // 成功时通知父组件
  handleError: PropTypes.func, // 报错时点击关闭 通知父组件
  params: PropTypes.object, // 下达指令的入参数据，
  tradeType: PropTypes.string, // 哪种簿记或者指令
};
export default connect(({ businessOrderM }) => ({ businessOrderM }))(OrderComponet);
